package com.ttl.bc.ap.purchaseorder.chemical;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import com.sun.org.apache.bcel.internal.generic.DMUL;
import com.ttl.bc.ap.ap.bean.BCAPBean;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceSubShowBean;
import com.ttl.bc.ap.purchaseorder.bean.BCPurchaseOrderBean;
import com.ttl.bc.ap.purchaseorder.bean.BCPurchaseOrderSubBean;
import com.ttl.bc.ap.purchaseorder.db.BCPurchaseOrderDAO;
import com.ttl.bc.ic.stktransfer2.BCStkTransfSub2;
import com.ttl.bc.ic.stktransfer2.BCStkTransfer2;
import com.ttl.bc.ic.stktransfer2.BCStkTransfer2DAO;
import com.ttl.common.util.CommonUtils;
import com.ttl.common.util.Page;

public class ChemicalBO {

	public List<CalStockItemBean> cal(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		String dept = request.getParameter("dept");

		String shelf = getShelf(dept);
		
		String itemsArray[] = null;//{"2-", "3-"};
		
		return new ChemicalDAO().cal("10",shelf, itemsArray);
	}

	public List<CalStockItemBean> createpo(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		String dept = request.getParameter("dept");

		String shelf = getShelf(dept);

		ChemicalCheckBoxForm chk_list = (ChemicalCheckBoxForm)form;
		if(chk_list.getCheckboxValue()!=null) {
			for (int i = 0; i < chk_list.getCheckboxValue().length; i++) {
				System.out.println(chk_list.getCheckboxValue()[i]);
			}
		}
		
		return new ChemicalDAO().createpo(shelf, chk_list.getCheckboxValue());
	}

	public List<ChemicalHistoryBean> chemicalHistory(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		String dept = request.getParameter("dept");
		String itemCode[] ={ request.getParameter("itemCode") };

		String shelf = getShelf(dept);
		
		List<ChemicalHistoryBean> hitoryList = new ChemicalDAO().chemicalHistory("10", shelf, itemCode);
		
		return hitoryList;
	}

	private String getShelf(String dept) {
		String shelf = "";

		if(dept.equalsIgnoreCase("PD")) {
			shelf = "12";
		}else if(dept.equalsIgnoreCase("YD")) {
			shelf = "16";
		}else if(dept.equalsIgnoreCase("FF")) {
			shelf = "17";
		}
		return shelf;
	}

	public List<ChemicalHistoryBean> get12months(String itemCode) {
		ArrayList<ChemicalHistoryBean> al = new ArrayList<ChemicalHistoryBean>();
		
		Calendar cal = Calendar.getInstance(Locale.US);
		int yStart = cal.get(Calendar.YEAR)-1;
		int mStart = cal.get(Calendar.MONTH)+1;
		
		for (int i = 0; i < 12; i++) {
			ChemicalHistoryBean his = new ChemicalHistoryBean();
			his.setItemCode(itemCode);
			
			if(mStart>12) {
				mStart = 1;
				yStart++;
			}
//			cal.set(yStart,mStart,1);
			his.setMonth_(mStart);
			his.setYear_(yStart);
			mStart++;
			
			his.setUsedQty(0f);
			al.add(his);
		}
		return al;
	}

	public List<CalStockItemBean> calItem(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		String dept = request.getParameter("dept");

		String shelf = getShelf(dept);
		
		String itemCode=request.getParameter("itemCode");
		String itemsArray[] = {itemCode};
		
		return new ChemicalDAO().cal("10",shelf, itemsArray);
	}

	public static String getBeginLastMonth(int i) {
		Calendar current  = Calendar.getInstance();
		
		int mm = current.get(Calendar.MONTH)+1;
		int yyyy = current.get(Calendar.YEAR);
		
		if(i==12) {
			yyyy -=1;
		}else {
			if(mm<i) {
				mm = i-mm;
				yyyy -=1;
			}else {
				mm = mm-i;
			}
		}	
		return ""+yyyy+"-"+mm+"-1";
	}

	public static String getEndLastMonth() {
		Calendar current  = Calendar.getInstance();
		
		int mm = current.get(Calendar.MONTH);
		int yyyy = current.get(Calendar.YEAR);
		int dd = 0;
		if(mm==0) {
			yyyy -=1;
			mm = 12;
			dd = 31;
		}else if(mm==1 || mm==3 || mm==5 || mm==7 || mm==8 || mm==10) {
			dd = 31;
		}else if(mm==4 || mm==6 || mm==9 || mm==11) {
			dd = 30;
		}else {	
			if(yyyy%4==0) {
				dd = 29;
			}else {
				dd = 28;
			}
		}
		return ""+yyyy+"-"+mm+"-"+dd;
	}

	@SuppressWarnings("unchecked")
	public boolean add(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		// ###########   Start : Add Table BCPurchaseOrder, BCPurchaseOrderSub  #########
		BCPurchaseOrderBean  po = setPurchaseOrderObject(form, request);			
		ChemicalDAO dao = new ChemicalDAO();
		String hql = "FROM BCPurchaseOrderBean WHERE docNo = '"+po.getDocNo()+"' ";
		List<BCPurchaseOrderBean> al = (List<BCPurchaseOrderBean>)dao.find(hql);
		if(al!=null && al.size()==0) {
			dao.add(po);
		}else {
			String maxDocNo = CommonUtils.getMaxBCPurchaseOrderDocNo("PO1-DC-");
			po.setDocNo(maxDocNo);
			dao.add(po);
		}
		request.setAttribute("docNoPrint", po.getDocNo());
		// ###########   END : Add Table BCPurchaseOrder, BCPurchaseOrderSub  #########		
		request.setAttribute("message", "บันทึกข้อมูลใหม่เรียบร้อย");
//		request.setAttribute("forwardPage", "3;url=chemicalpo.do?mode=blank&dept=");
//		request.setAttribute("itemFind", request.getParameter("dept"));
		System.out.println("request.getParameter(dept)"+request.getParameter("dept"));

		String dept = request.getParameter("dept");
		
		request.setAttribute("forwardPage", "3;url=chemicalpo.do?mode=showFind&dept="+dept+"&itemFind=");
		
		request.setAttribute("itemFind", po.getDocNo());
		return true;
	}

	private BCPurchaseOrderBean setPurchaseOrderObject(ActionForm form,
			HttpServletRequest request) {
		
		String userName = (String)request.getSession().getAttribute("userName");			

		BCPurchaseOrderBean po = new BCPurchaseOrderBean();
		
		ChemicalCheckBoxForm c = (ChemicalCheckBoxForm)form;
		po.setDocNo(c.getDocNo());
		
		po.setDocDate(CommonUtils.convertStringToDate(c.getDocDate()));
		po.setDepartCode(c.getDepartCode());
		po.setApCode(c.getApCode());
		po.setCurrencyCode(c.getCurrencyCode());
		po.setProjectCode(c.getProjectCode());
		po.setSumOfItemAmount(c.getSumOfItemAmount());
		po.setDiscountAmount(c.getDiscountAmount());
		po.setAfterDiscount(po.getSumOfItemAmount()-po.getDiscountAmount());
		po.setBeforeTaxAmount(po.getSumOfItemAmount());
		po.setTaxAmount(c.getTaxAmount());
		po.setTotalAmount(c.getTotalAmount());
		po.setNetAmount(po.getTotalAmount());
	
		po.setIsConfirm(1);		
		po.setPoStatus(0);
		po.setBillStatus(0);
		po.setIsCancel(0);
		po.setIsCompleteSave(1);		
		po.setBillGroup("");
		po.setCreatorCode(userName);
		po.setCreateDateTime(new Date());

		try {
			po.setMyDescription(new String(c.getMyDescription().getBytes("ISO8859_1"),"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		po.setIttl_purchaseCode(c.getIttl_purchaseCode());
		po.setTempMyDesc2(c.getTempMyDesc2());
		po.setTempMyDesc4(request.getParameter("dept"));
//		System.out.println(po.getTempMyDesc4());
		
		po.setTaxType(c.getTaxType());
		po.setTaxRate(c.getTaxRate());
	
		HashSet<BCPurchaseOrderSubBean> hashSet = new HashSet<BCPurchaseOrderSubBean>();
		
		for(int i=0; i<c.getItemCode().length; i++) {
			BCPurchaseOrderSubBean sub = new BCPurchaseOrderSubBean();
			sub.setItemCode(c.getItemCode()[i]);
			
			sub.setDocDate(po.getDocDate());
			sub.setApCode(po.getApCode());
			sub.setDepartCode(po.getDepartCode());
			sub.setItemName(c.getItemName()[i]);
			sub.setWhCode("10");
			sub.setShelfCode("10");
			sub.setQty(c.getQty()[i]);
			sub.setRemainQty(sub.getQty());
			sub.setPrice(c.getPrice()[i]);
			
			sub.setAmount(c.getAmount()[i]);
			sub.setNetAmount(sub.getAmount());
			sub.setHomeAmount(sub.getAmount());
			
			try {
				float aa = Float.valueOf(c.getLineItemDiscountAmount()[i]);
				sub.setDiscountAmount(aa);
			}catch (Exception e) {
				sub.setDiscountWord(c.getLineItemDiscountAmount()[i]);
				sub.setDiscountAmount((sub.getQty()*sub.getPrice())-sub.getAmount());
			}
			
			if(sub.getDiscountAmount()==0) {
				sub.setDiscountWord(null);
			}
			
			if(sub.getDiscountWord()==null) {
				double  a= sub.getDiscountAmount()/(sub.getQty()*sub.getPrice())*100;
				java.text.DecimalFormat dfm = new java.text.DecimalFormat("0.00");
				sub.setDiscountWord(dfm.format(a)+"%");
			}
			
			sub.setUnitCode(c.getUnitCode()[i]);
			sub.setIttl_unitName("KGS.");			
			sub.setProjectCode(po.getProjectCode());
			sub.setCurrencyCode(po.getCurrencyCode());
			sub.setIsCancel(0);
			sub.setLineNumber(i);
			
			sub.setTaxRate(po.getTaxRate());
			sub.setPackingRate1(1f);
			sub.setPackingRate2(1f);
			sub.setIttl_purchaseCode(po.getIttl_purchaseCode());	
			
			sub.setCreatorCode(userName);
			sub.setCreateDateTime(po.getCreateDateTime());
			
			sub.setBcPurchaseOrder(po);
			hashSet.add(sub);
		}
		po.setBcPurchaseOrderSubs(hashSet);
		return po;
	}

	@SuppressWarnings("rawtypes")
	public BCAPBean findAPofItem(List<CalStockItemBean> al) {
		BCAPBean ap = new BCAPBean();
		
		String itemCode = "";
		for (CalStockItemBean c : al) {
			itemCode = c.getItemCode();
		}
		
		String hql = "From BCAPInvoiceSubShowBean Where itemCode='"+itemCode+"' Order by docDate desc";
		List list = new ChemicalDAO().find(hql);
		if(list!=null && list.size()>0) {
			BCAPInvoiceSubShowBean i = (BCAPInvoiceSubShowBean)list.get(0);
			ap.setCode(i.getApCode());
		}
		
		hql = "From BCAPBean Where code='"+ap.getCode()+"'";
		list = new ChemicalDAO().find(hql);
		if(list!=null && list.size()>0) {
			BCAPBean a = (BCAPBean)list.get(0);
			ap.setName1(a.getName1());
		}
		
		return ap;
	}

	public boolean showFind(HttpServletRequest request) throws Exception {

		String userName = (String)request.getSession().getAttribute("userName");
		String dept = request.getParameter("dept");
		request.setAttribute("dept", dept);
		String	itemFind = CommonUtils.getItemFind(request);
										
		String hql = "";
		if(itemFind==null||itemFind.trim().equals("")) {
			hql = "FROM BCPurchaseOrderBean " +
					 " WHERE upper(creatorCode)='"+userName.toUpperCase()+"' " +
					 " and docNo like 'PO1-DC%' "+
					 " ORDER BY docNo desc ";			
		}else {
			hql = "FROM BCPurchaseOrderBean " +
					 " WHERE upper(creatorCode)='"+userName.toUpperCase()+"' " +
					 " and docNo like '%"+itemFind.trim()+"%' "+					 
					 " and docNo like 'PO1-DC%' "+
					 " ORDER BY docNo desc";
		}
						
		return Page.showPage(request, hql);
	}

	@SuppressWarnings("rawtypes")
	public boolean view(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		String docNo = request.getParameter("docNo");
		String hql = "FROM BCPurchaseOrderBean WHERE docNo='"+docNo+"'";
		List al = new ChemicalDAO().find(hql);
		if(al!=null && al.size()>0) {
			
			request.setAttribute("p", al.get(0));
			
			BCPurchaseOrderBean s = (BCPurchaseOrderBean)al.get(0);
			request.setAttribute("sub", s.getBcPurchaseOrderSubs());
			
			return true;
		}else {
			return false;
		}
	}

	public boolean update(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		BCPurchaseOrderBean  po = setPurchaseOrderObject(form, request);
		
		request.setAttribute("message", "แก้ไขข้อมูลเรียบร้อย");
		request.setAttribute("forwardPage", "3;url=chemicalpo.do?mode=showFind&itemFind=");
		request.setAttribute("itemFind", po.getDocNo());
		
		return 	new ChemicalDAO().update(po.getDocNo(),po);
	}

	public boolean delete(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		BCPurchaseOrderBean  po = setPurchaseOrderObject(form, request);
		request.setAttribute("message", "ยกเลิกข้อมูลเรียบร้อย");
		request.setAttribute("forwardPage", "3;url=chemicalpo.do?mode=showFind&itemFind=");
		
		request.setAttribute("itemFind", po.getDocNo());

		return 	new ChemicalDAO().cancel(po.getDocNo());
	}
}
